﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using com.paypal.sdk.util;

namespace ECSE6770
{
    public static class OrderHistoryManager
    {
        /// <summary>
        /// Stores the details of a user's shopping cart and Paypal response in the database.
        /// </summary>
        /// <param name="cart"></param>
        /// <param name="decoder"></param>
        /// <param name="rawResponse"></param>
        public static void LogOrder(Cart cart, NVPCodec decoder, string rawResponse)
        {
            var db = ContextManager.CurrentDb;
            var order = new OrderHistory
            {
                DatePosted = DateTime.Now,
                PayPalExtendedData = rawResponse,
                PayPalResult = decoder["ACK"],
                //User = ContextManager.CurrentUser.Interop,
                UserInteropId = ContextManager.CurrentUser.Interop.Id,
                TotalCost = cart.TotalCost,
                PayPalTransaction = decoder["TRANSACTIONID"]
            };

            foreach (Product p in cart.ProductEntityItems())
                order.Products.Add(p);

            db.OrderHistories.Add(order);
            db.SaveChanges();
        }

        public static List<OrderHistory> CurrentUserOrders()
        {
            int id = ContextManager.CurrentUser.Interop.Id;
            return ContextManager.CurrentDb.OrderHistories.Where(o => o.UserInteropId == id).ToList();
        }

        public static List<OrderHistory> AllOrders()
        {
            return ContextManager.CurrentDb.OrderHistories.OrderByDescending(o => o.DatePosted).ToList();
        }
    }
}